<template>

  <div>
      <!-- 用户编辑 -->
      <el-dialog title="用户编辑" :visible.sync="editDialogFormVisible" width="30%">
        <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="头像" prop="name">
                <el-upload
                class="avatar-uploader"
                action="http://localhost:8080/api/file/fileUpload"
                :headers="headers"
                name="file"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                    <img v-if="editForm.avatar != null" :src="'http://localhost:8888/file/getImgById?id='+editForm.avatar" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户名" prop="username">
                <el-input v-model="editForm.username" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="性别">
                <el-radio-group v-model="editForm.sex">
                <el-radio :label="1">男</el-radio>
                <el-radio :label="0">女</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="身份证号码" prop="idCard">
                <el-input v-model="editForm.idCard" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="电话号码" prop="phone">
                <el-input v-model="editForm.phone" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="家庭住址">
                <el-input v-model="editForm.address" style="width:300px;"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email" style="width:300px;"></el-input>
            </el-form-item>
              <el-form-item label="状态">
                <el-radio-group v-model="editForm.status">
                <el-radio :label="0">正常</el-radio>
                <el-radio :label="1">停用</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="editDialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateEdit()">确 定</el-button>
        </div>
      </el-dialog>
       <!-- 分配角色 -->
       <el-dialog title="分配角色" :visible.sync="roleDialogFormVisible" width="30%">
        <el-radio-group v-model="roleForm.roleId">
            <el-radio v-for="item in roles" :key="item.id"  :label="item.id">{{item.name}}</el-radio>
        </el-radio-group>
        <div slot="footer" class="dialog-footer">
            <el-button @click="roleDialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateRole()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 菜单查询 -->
      <el-form :inline="true" :model="queryForm" class="demo-form-inline" style="border:1px solid #DCDFE6;padding: 10px;">
        <el-form-item label="用户名">
            <el-input v-model="queryForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="身份证号码">
            <el-input v-model="queryForm.idCard" placeholder="请输入身份证号码"></el-input>
        </el-form-item>
        <el-form-item label="电话号码">
            <el-input v-model="queryForm.phone" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="性别">
            <el-select v-model="queryForm.sex" placeholder="请选择性别">
                <el-option label="无" value="">无</el-option>
                <el-option label="女" value="0">女</el-option>
                <el-option label="男" value="1">男</el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="状态">
            <el-select v-model="queryForm.status" placeholder="请选择状态">
                <el-option label="正常" value="0">正常</el-option>
                <el-option label="停用" value="1">停用</el-option>
            </el-select>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="onSubmit()">查询</el-button>
        </el-form-item>
       </el-form>
       <!-- 显示区域 -->
       <el-container style="border:1px solid #DCDFE6;padding: 10px;margin-top:10px">
           <el-table
            :data="users"
            stripe
            style="width: 100%">
            <el-table-column
            label="id"
            sortable
            width="60">
            <template slot-scope="scope">
                  <span >{{ scope.row.id }}</span>
            </template>
            </el-table-column>
            <el-table-column
            label="头像"
            width="70">
            <template slot-scope="scope">
                 <el-avatar v-if="scope.row.avatar != null" shape="square" size="medium" :src="'http://localhost:8888/file/getImgById?id='+ scope.row.avatar"></el-avatar>
                 <el-avatar v-else  shape="square" icon="el-icon-user-solid"></el-avatar>
            </template>
            </el-table-column>
            <el-table-column
            label="用户名"
            sortable
            width="115">
            <template slot-scope="scope">
                <span >{{ scope.row.username }}</span>
            </template>
            </el-table-column>
             <el-table-column
            label="性别"
            width="60">
            <template slot-scope="scope">
                 <el-tag
                :type="scope.row.sex===0 ? 'success' : 'primary'"
                disable-transitions>{{scope.row.sex == 0 ? "女":"男"}}</el-tag>
            </template>
            </el-table-column>
             <el-table-column
            label="身份证号码"
            sortable
            width="160">
            <template slot-scope="scope">
                <span>{{ scope.row.idCard }}</span>
            </template>
            </el-table-column>
            <el-table-column
            label="电话号码"
            sortable
            width="140">
            <template slot-scope="scope">
               <span>{{ scope.row.phone }}</span>
            </template>
            </el-table-column>
            <el-table-column
            label="家庭住址"
            sortable
            width="130">
            <template slot-scope="scope">
                <span >{{scope.row.address}}</span>
            </template>
            </el-table-column>
            <el-table-column
            label="邮箱"
            sortable
            width="150">
            <template slot-scope="scope">
                <span >{{scope.row.email}}</span>
            </template>
            </el-table-column>
            <el-table-column
            label="状态"
            width="70">
            <template slot-scope="scope">
                 <el-tag
                :type="scope.row.status===0 ? 'success' : 'info'"
                disable-transitions>{{scope.row.status===0 ? "正常":"停用"}}</el-tag>
            </template>
            </el-table-column>
            
            <el-table-column label="操作"  width="330">
                <template slot-scope="scope">
                    <el-button
                    size="mini"
                    type="primary"
                    plain
                    @click="hasRole(scope.$index, scope.row)">分配角色</el-button>
                    <el-button
                    size="mini"
                    type="primary"
                    plain
                    @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-popover
                    placement="top"
                    width="160"
                    trigger="click"
                    v-model="scope.row.resetVisible">
                    <p>您确定要重置密码吗？</p>
                    <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="scope.row.resetVisible = false">取消</el-button>
                        <el-button type="primary" size="mini" @click="handleReset(scope.$index, scope.row)">确定</el-button>
                    </div>
                    <el-button 
                    style="margin-left:10px"
                    slot="reference"
                    size="mini"
                    type="primary"
                    plain>重置密码</el-button>
                    </el-popover>
                    <el-popover
                    placement="top"
                    width="160"
                    trigger="click"
                    v-model="scope.row.visible">
                    <p>您确定要删除吗？</p>
                    <div style="text-align: right; margin: 0">
                        <el-button size="mini" type="text" @click="scope.row.visible = false">取消</el-button>
                        <el-button type="primary" size="mini" @click="handleDelete(scope.$index, scope.row)">确定</el-button>
                    </div>
                    <el-button 
                    style="margin-left:10px"
                    slot="reference"
                    size="mini"
                    type="danger">删除</el-button>
                    </el-popover>
                </template>
            </el-table-column>
        </el-table>
       </el-container>
       <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.current"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryForm.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataSize">
        </el-pagination>
  </div>
</template>

<script>
import Qs from 'qs';
export default {
    data(){
        return{
            headers:{
                token: window.sessionStorage.getItem('token')
            },
            editDialogFormVisible: false,//编辑用户界面是否可见
            roleDialogFormVisible:false,//分配角色界面是否可见
            dataSize:400,// 数据总数
            queryForm:{
                username:"",
                idCard:"",
                phone:"",
                sex:"",
                status: "",
                current:1,
                size:10
            },
            editForm:{},
            roleForm:{
                roleId:1,
                userId:1
            },
            roles:{},//所有用户
            users:[],
             rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入用户密码', trigger: 'change' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                idCard: [
                    { required: true, message: '请填写身份证号码', trigger: 'blur'}
                ],
                phone: [
                    { required: true, message: '请填写电话号码', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请填写邮箱地址', trigger: 'blur' }
                ]
            }
        }
    },
    created(){
        this.onSubmit();
    },
    methods:{
        //提交
        async onSubmit() {
            const res = await this.$http.get("/user/listUsers",{params:this.queryForm})
            this.users=res.data.data.records;
            this.dataSize =res.data.data.total;
        },
        // 编辑按钮
        handleEdit(index,row){
            this.editDialogFormVisible = true;
            this.editForm = row;
        },
        //提交修改用户信息
        async updateEdit(){
            const res = await this.$http.post("/user/updateUser",Qs.stringify(this.editForm))
            if(res.data.code === 200){
                 this.$message({
                    message: res.data.msg,
                    type: 'success'
                });
                this.editDialogFormVisible = false;
                // 刷新当前页面
                this.onSubmit();
            }else{
                 this.$message.error(res.data.msg);
            }
        },
        // 分配角色按钮
        async hasRole(index,row){
            var res = await this.$http.get("/role/listRoles");
            this.roles =res.data.data;
            //查询当前账号角色
            this.roleDialogFormVisible = true;
            res = await this.$http.get("/userrole/getRoleIdByUid?uid="+row.id);
            this.roleForm.userId = row.id;
            this.roleForm.roleId = res.data.data;
        },
        //更新用户角色
        async updateRole(){
            // 通过删除按钮根据id删除菜单数据
            const res = await this.$http.post("/userrole/saveUserRole",Qs.stringify(this.roleForm))
            if(res.data.code === 200){
                this.roleDialogFormVisible = false;
                this.$message({
                    message: res.data.msg,
                    type: 'success'
                });
                this.onSubmit();
            }else{
                this.$message.error(res.data.msg);
            }
        },
        // 重置密码
        async handleReset(index,row){
            row.resetVisible = false;
            // 通过删除按钮根据id删除菜单数据
            const res = await this.$http.post("/user/resetUserPassword",Qs.stringify({id:row.id}))
            if(res.data.code === 200){
                this.$message({
                    message: res.data.msg,
                    type: 'success'
                });
                this.onSubmit();
            }else{
                this.$message.error(res.data.msg);
            }
        },
        // 删除按钮
        async handleDelete(index,row){
            row.visible = false;
            // 通过删除按钮根据id删除菜单数据
            const res = await this.$http.post("/user/deleteUser",Qs.stringify({id:row.id}))
            if(res.data.code === 200){
                this.$message({
                    message: res.data.msg,
                    type: 'success'
                });
                this.onSubmit();
            }else{
                this.$message.error(res.data.msg);
            }
        },
        // 每叶总数改变
        handleSizeChange(val) {
             this.queryForm.size  = val;
             this.onSubmit();
        },
        //当前页
        handleCurrentChange(val) {
            this.queryForm.current = val;
            this.onSubmit();
        },
          // 处理头像提交成功事件
    handleAvatarSuccess(res, file) {
      if(res.code === 200){
         this.$message({
          message: res.msg,
          type: 'success'
        });
        this.editForm.avatar = res.data;
        this.imageUrl = URL.createObjectURL(file.raw);
      }else{
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'error'
        });
      }
       
    },
    //文件上传前处理
    beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isJPG) {
        //     this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        // return isJPG && isLt2M;
        return isLt2M;
    }

    }

}
</script>

<style scoped>
 .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  /* 文件上传 */
.el-upload {
    border: 1px dashed #750e0e;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
.el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
  }
  .avatar-uploader{
    width: 100px;
    height: 100px;
    border: 1px solid #b2b8c0;
    margin-left: 50px;
  }
</style>